package com.demo.mongo.listener;

import com.demo.mongo.annontion.AutoIncKey;
import com.demo.mongo.entity.SeqInfo;
import lombok.AllArgsConstructor;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * 保存 mongo 文档监听类
 *
 * @author YT
 * @date 2019-08-19
 */
@Component
@AllArgsConstructor
public class AutoIncKeyEventListener extends AbstractMongoEventListener<Object> {

    private final MongoTemplate mongoTemplate;

    @Override
    public void onBeforeConvert(BeforeConvertEvent<Object> event) {
        final Object source = event.getSource();
        if (source != null) {
            ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {
                @Override
                public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                    // 将一个字段设置为可读写
                    ReflectionUtils.makeAccessible(field);
                    // 如果字段添加 @AutoIncKey 注解
                    if (field.isAnnotationPresent(AutoIncKey.class) && field.get(source) instanceof Number && field.getLong(source) == 0) {
                        // 设置自增 ID
                        field.set(event, getNextId(event.getClass().getSimpleName()));
                    }
                }
            });
        }
    }

    /**
     * 获取下一个自增 ID
     *
     * @param collName
     * @return
     */
    private Long getNextId(String collName) {
        Query query = new Query(Criteria.where("collName").is(collName));
        Update update = new Update();
        update.inc("seqId", 1);
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.upsert(true);
        options.returnNew(true);
        SeqInfo seq = mongoTemplate.findAndModify(query, update, options, SeqInfo.class);
        return seq.getSeqId();
    }
}
